package cn.itcast.controller;

import cn.itcast.domain.Account;
import cn.itcast.group.AddGroup;
import cn.itcast.service.AccountService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/account")
public class AccoutController {
    @Autowired
  private AccountService accountService;
@GetMapping
    public List<Account> findAll(){
    System.out.println("ssm搭建成功");
        return accountService.findAll();
    }

    @GetMapping("/{id}")
    public Account findall(@PathVariable Integer id){
        Account byId = accountService.findById(id);
        return byId;
    }

    @PostMapping
    public Object add(@RequestBody @Validated(AddGroup.class) Account account, Errors errors) {
        HashMap result=new HashMap<>();
        HashMap errorInfo=new HashMap<>();
        accountService.add(account);
        for (FieldError error : errors.getFieldErrors()) {
            errorInfo.put(error.getField(),error.getDefaultMessage());
        }
        if (errorInfo.size()==0){
            result.put("flag",true);
            result.put("code",200);
            result.put("message","reg success");
        }else {
            result.put("flag",false);
            result.put("code",400);
            result.put("message","reg error");
        }

        return result;
    }


    @PutMapping()
    public void update(@RequestBody @Validated(Update.class) Account account) {
        System.out.println(account);
        accountService.update(account);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id){
        accountService.delete(id);
    }
}
